<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="850px" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="cloud-machine-form">
      <div class=" flex-box">
        <div class="flex" style="align-items: center;">
          
      
        <div class="flex-col">
          <div class="flex-col-title">
            <img class="yunjiq" src="@/assets/img/yunji-1.png" alt="云机挂q">
          </div>
          <div class="flex-col-tips">稳定挂机 换绑无忧
          </div>
          
        </div>
        <div class="flex-r">
           <span>{{ yudou }}</span>虞豆/台/月
          <img class="rent-bg" src="@/assets/img/rent-bg.png" alt="">
          </div>
  </div>
           <div class="flex-col-two-tips">为保障云机正常运行，每台云机最多可登录100个账号。平台会持续优化云机资源，提升挂Q效率与稳定性。
          </div>
      </div>
      <!-- <div class="flex-box">
        说明：
        为保障云机正常运行，每台云机最多可挂150个QQ账号。平台会持续优化云机资源，提升挂Q效率与稳定性。
      </div> -->
      <template v-if="dialogType === 'add'">
    
        <el-form-item label="租用数量" prop="count">
          <el-input-number v-model="form.count" :min="1"  style="width: 200px"
            @change="calculateCost" />
          <div class="form-tip">请输入需要租用的云机数量</div>
        </el-form-item>
      </template>

      <!-- 续费模式：显示云机编号和到期时间 -->
      <template v-if="dialogType === 'renew'">
        <!-- <el-form-item label="云机编号" prop="id">
          <el-input v-model="form.id" disabled style="width: 100%" />
        </el-form-item> -->

        <el-form-item label="到期时间" prop="expireTime">
          {{parseTime(form.expireTime, '{y}-{m}-{d}')}}
         
        </el-form-item>
      </template>

      <!-- 租用时长/续费时长 -->
      <el-form-item :label="durationLabel" prop="month">
        <el-input-number v-model="form.month" :min="1" :max="36" style="width: 200px" @change="calculateCost" /> 
        月
      </el-form-item>
      <!-- 所需虞豆 -->
      <el-form-item label="所需虞豆">
        <div class="beans-display">
          <span class="beans-value">{{ form.money }}</span>
        </div>
      </el-form-item>

        <el-form-item label="自动续费" prop="renewal">
           <el-switch v-model="form.renewal" :active-value="2" :inactive-value="1" active-color="#6C5DD3" inactive-color="#999">
          </el-switch>
      </el-form-item>
      
        <el-form-item label="剩余虞豆">
          <div class="beans-display">
            <span style="font-size: 16px;"  v-if="shopInfo">{{shopInfo.campNumber}}</span>
            <span style="font-size: 16px;"  v-else>0</span>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit" >
        {{ submitButtonText }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { rentCloudMachine, renewal } from '@/api/tenantApis/cloudMachine'

export default {
  name: 'CloudMachineDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add', // 'add' 或 'renew'
      validator: value => ['add', 'renew'].includes(value)
    },
    machineData: {
      type: Object,
      default: () => ({})
    },
    yudou:{
      type: [Number , String],
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      submitLoading: false,
      form: {
        availableCount: 0,
        count: 1,
        id: '',
        expireTime: '',
        month: '',
        money: 0,
        renewal:2,
        machineType:1
      },
      rules: {
        count: [
          { required: true, message: '请输入租用数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '租用数量不能小于1', trigger: 'blur' }
        ],
        month: [
          { required: true, message: '请选择租用时长', trigger: 'change' }
        ]
      },


    }
  },
  computed: {
    dialogType() {
      return this.type
    },
    dialogTitle() {
      return this.dialogType === 'add' ? '租用云机' : '续费云机'
    },
    durationLabel() {
      return this.dialogType === 'add' ? '租用时长' : '续费时长'
    },
    submitButtonText() {
      return this.dialogType === 'add' ? '立即租用' : '立即续费'
    },
      shopInfo() {
      return this.$store.getters.shopInfo;
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
        if (newVal) {
          this.initForm()
        }
      },
      immediate: true
    },
    machineData: {
      handler(newVal) {
        if (newVal && this.dialogVisible) {
          this.initForm()
        }
      },
      deep: true
    }
  },
  methods: {
    initForm() {
      // 重置表单
      this.form = {
        availableCount: 0,
        count: 1,
        id: '',
        expireTime: '',
        month: '',
        renewal:2,
        machineType:1
      }
      this.form.money = this.yudou
      if (this.dialogType === 'add') {
        // 新增模式：获取可租数量
      
      } else if (this.dialogType === 'renew') {
        console.log('this.machineData', this.machineData)
        // 续费模式：设置云机信息
        this.form.id = this.machineData.id || ''
        this.form.expireTime = this.machineData.expireTime || ''
        this.form.renewal = this.machineData.renewal || 2
      }

      // 清除验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

 

    // 计算所需虞豆
    calculateCost() {
      if (!this.form.month) {
        this.form.money = this.yudou
        return
      }
      let count = 1
      if (this.dialogType === 'add' && this.form.count) {
        count = this.form.count
      }
      this.form.money = count * this.form.month * this.yudou
    },

    // 提交表单
    handleSubmit() {
      let that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          let price = `<span style="color:red">${this.form.money}</span>`;
         let cont =  this.dialogType === 'add' ? '租用' : '续费'
          this.$confirm(`您正在${cont}${this.form.count}台云机,需要耗费 ${price}虞豆,确认继续吗？`,{dangerouslyUseHTMLString: true}).then(() => {
            that.submitForm()
          })
        }
        
      })
    },

    // 提交表单数据
    async submitForm() {
      this.submitLoading = true

      try {
        const submitData = {
          type: this.dialogType,
          month: this.form.month,
          money: this.form.money,
          renewal:this.form.renewal,
          machineType:this.form.machineType
        }

        if (this.dialogType === 'add') {
          submitData.count = this.form.count
        } else if (this.dialogType === 'renew') {
          submitData.id = this.form.id
        }

        // 调用相应的API
        if (this.dialogType === 'add') {
          await rentCloudMachine(submitData)
        } else {
          await renewal(submitData)
        }

        this.$message.success(
          this.dialogType === 'add' ? '租用成功' : '续费成功'
        )

        this.handleClose()
        this.$emit('success')

      } catch (error) {
        console.error('提交失败:', error)
        // this.$message.error('操作失败，请重试')
      } finally {
        this.submitLoading = false
      }
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.cloud-machine-form {
  .form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }

  .beans-display {


    .beans-value {
      font-size: 20px;
      font-weight: bold;
      color: #f40;
      margin-right: 4px;
    }

    .beans-unit {
      font-size: 14px;
      color: #606266;
    }
  }
}

.dialog-footer {
  text-align: right;
}

.flex-box {

  background: url('../../../../assets/img/yunji-bg.png')  no-repeat;
  background-size: 100% 100%;
  border-radius: 10px;
  padding: 7px 0px 24px 30px;
  justify-content: space-between;
  align-items: center;
}

.flex-col-title {
  font-size: 20px;

}
.flex-col {
  flex: 1;
}
.flex-col-tips {
  font-size: 20px;
  color: #030C22;
}
.flex-col-two-tips {
  font-size: 13px;
  color: #999;
  margin-top: 6px;
}

.flex-r {
  color: #6C7293;


  span {
    color: #6C5DD3;
    font-size: 20px;
  }
}
::v-deep {
  .el-form-item {
    margin-bottom: 16px;
  }
}
.rent-bg {
  vertical-align: middle;
  width: 150px;
}
.yunjiq {
  width: 120px;
}
</style>
